// Bot para crear sesiones de Wave

package com.wavecoler.coach.bots;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;

import com.google.gson.Gson;
import com.google.wave.api.AbstractRobot;
import com.google.wave.api.Blip;
import com.google.wave.api.Context;
import com.google.wave.api.JsonRpcResponse;
import com.google.wave.api.Wavelet;
import com.google.wave.api.event.WaveletCreatedEvent;
import com.google.wave.api.event.WaveletSelfAddedEvent;
import com.google.wave.api.impl.GsonFactory;
@SuppressWarnings("serial")
public class BotSessions extends AbstractRobot {

	private static final Logger LOG = Logger.getLogger(BotSessions.class
			.getName());
	private static final Gson SERIALIZER = new GsonFactory().create();

	// Active Data API register information for Web in a Box
	// private String
	// consumerToken="multiplebots.colertec@wavecoler.lag.itesm.mx";
	// private String
	// tokenSecret="LLzVy7oHvIe_kxzMurUnR5sQgUlvc6kqF0tDbXcUjmO0GPXr";

//	private String consumerToken = "colertec@wavecoler.lag.itesm.mx";
//	private String tokenSecret = "qoF8uZg2rCC-4I_VrmCfJ1BkAqSZbLTRJdzH2pWWLDIKAJk8";

	private String consumerToken = "wavecoler@wavecoler.lag.itesm.mx";
//	private String tokenSecret = "60j8RhGDCtZxSiY1N3pFPCyHEOtXxaOoMCdUWbHfQEZBG-Xl";

	private String tokenSecret = "OEwS2RZlV7Ry9T7bDjGeh7QE9C9kWqzxmy697pcnQ4f77F06";
	// Active Data API register information for Google Wave
	private String CONSUMER_KEY = "358338293703";
	private String CONSUMER_SECRET = "vQZvYiGf0YDlBM856sbXaqxA";

	public BotSessions() {
		// Register data for bot in GoogleWave
		/*
		 * String verificationToken=
		 * "AAOijR2fJkMZ73dZOAGx6mOpOpN6m12TCtiG0DLLCRY92WFEu4vE0anO5b1tJH7zk8k2YRu2eMSQOIL_W71bGVibbQDh_4LGhNaEVjE5dOupTLMO0F8Oe6EXcRXCBtXbLDk90XnmMOEOFzpx4UGyH2pE4VVHU2NJ3MA=="
		 * ; String securityToken="4656";
		 * setupVerificationToken(verificationToken, securityToken);
		 */

		// Registration on Google Wave
		setupOAuth(CONSUMER_KEY, CONSUMER_SECRET,
				"https://www-opensocial.googleusercontent.com/api/rpc");

		// Registration in WIAB
		setupOAuth(consumerToken, tokenSecret,
				"http://wavecoler.lag.itesm.mx:9898/robot/rpc");
		setAllowUnsignedRequests(true);
	}

	@Override
	protected String getRobotName() {
		return "BotSessions";
	}

	@Override
	protected String getRobotAvatarUrl() {
		return "http://dl.dropbox.com/u/7268008/kickabot.jpg";
	}

	@Override
	protected String getRobotProfilePageUrl() {
		return "http://multiplebots.colertec.appspot.com";
	}

	/**
	 * Called when the robot is added to wave. This method works as a sudo
	 * updater. It will create a new wave. Serialize it (This could be written
	 * to the datastore). Update the wavelet (The wavelet could be loaded back
	 * from the datastore). Send the update backs to wave.
	 */
	@Capability(contexts = { Context.SELF })
	@Override
	public void onWaveletSelfAdded(WaveletSelfAddedEvent event) {
		Wavelet wavelet = event.getWavelet();
		LOG.info("onWaveletSelfAdded wavelet");
		// wavelet.setTitle("Introducing Bot Sessions"); no funciona para WIAB
		// Blip blip = event.getBlip();
		Set<String> participants = new HashSet<String>();
		participants.add("aconstang@wavecoler.lag.itesm.mx");
		LOG.info("onWaveletSelfAdded participant added");
		Wavelet newWavelet = this.newWave(wavelet.getDomain(), participants); // used
																				// for
																				// GoogleWave
		// newWavelet.getRootBlip().append("The new wave!");
		// newWavelet.getRootBlip().reply().append("Some more content");
		appendLine(newWavelet.getRootBlip(), "The new wave!");
		// LOG.info("onWaveletSelfAdded modified root blip");
		List<JsonRpcResponse> responseList = null;
		try {
			responseList = submit(newWavelet,
					"http://wavecoler.lag.itesm.mx:9898/robot/rpc");
			if (responseList != null) {
				LOG.info("JsonResponse not null" + responseList);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// newWavelet.submitWith(wavelet);
		LOG.info("onWaveletSelfAdded new wavelet submitted");
		// Extract wave ID and wavelet ID. You could store this in the datastore
		// and update it at a later date.

		WaveId waveIdToStore = newWavelet.getWaveId();
		LOG.info("waveID = " + waveIdToStore);
		WaveletId waveletIdToStore = newWavelet.getWaveletId();
		LOG.info("waveletID = " + waveletIdToStore);
		// You could call this in a cron event and fetch the wave ID and wavelet
		// ID
		// to update the wavelet at any given point.

		Wavelet loadedWave = this.blindWavelet(waveIdToStore, waveletIdToStore);
		loadedWave.reply("\nSome updated stuff");
		try {
			responseList = submit(loadedWave,
					"http://wavecoler.lag.itesm.mx:9898/robot/rpc");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		LOG.info("wavelet loaded");
		// loadedWave.submitWith(wavelet); used in Google Wave, not WIAB

		/** event.getWavelet().getParticipants().add("barbyq14@googlewave.com"); **/
	}

	/**
	 * Called when a wavelet is created
	 */
	@Capability(contexts = { Context.SELF })
	@Override
	public void onWaveletCreated(WaveletCreatedEvent event) {
		LOG.info("onWaveletCreated");
		// Send a blip back to the original wavelet
		Wavelet wavelet = event.getWavelet();
		Wavelet orgWavelet = this.blindWavelet(wavelet.getWaveId(),
				wavelet.getWaveletId());
		List<JsonRpcResponse> responseList = null;
		orgWavelet.reply("\nThis looks like the new wavelet");
		try {
			responseList = submit(orgWavelet,
					"http://wavecoler.lag.itesm.mx:9898/robot/rpc");
			if (responseList != null) {
				LOG.info("JsonResponse not null" + responseList);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// orgWavelet.submitWith(wavelet);
	}

	public static void appendLine(Blip blip, String msg) {
		blip.at(blip.getContent().length()).insert(msg + "\n");
	}	
}